<template>
  <div class="app-container">

    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="添加分类">
        <el-input v-model="newCatelog" placeholder="分类名称" @keyup.enter.native="handlePostCatelog()" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlePostCatelog()">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list" style="width: 100%">

      <!-- <el-table-column label="ID" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="分类名" min-width="180">
        <template slot-scope="scope">
          <span style="margin-left: 8px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建日期" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.createdDate }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getList, deleteItem, createItem } from '@/api/catalog'

export default {
  data() {
    return {
      list: null,
      newCatelog: null,
      belong: this.$route.meta.belong,
      count: null
    }
  },
  created() {
    this.belong = this.$route.meta.belong
    this.fetchData()
  },
  methods: {
    fetchData() {
      const _this = this
      this.listLoading = true
      getList(this.belong).then(response => {
        // console.log(response.data.rows)
        this.list = response.data.rows
        this.list.forEach(item => {
          item.createdDate = _this.convertUtc(item.createdAt)
        })
        this.count = response.data.count
        this.listLoading = false
      })
    },
    handlePostCatelog() {
      if (this.newCatelog) {
        createItem(this.newCatelog, this.belong).then(response => {
          this.fetchData()
          this.newCatelog = null
        })
      }
    },
    handleDelete(index, row) {
      console.log('delete: ' + row.id)
      deleteItem(row.id).then(response => {
        this.fetchData()
      })
    },
    convertUtc(utc) {
      const date = new Date(utc)
      return date.toLocaleString('zh-CN', { hour12: false })
    }

  }
}
</script>

<style lang="less" scoped>
.preview-img{
    max-width: 120px;
    max-height: 120px;
}
</style>
